<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <BasicForm @register="registerForm" />
    <Row>
      <Col :span="6" style="display: flex; justify-content: center; align-items: center">
        {{ t('routes.table.accountManagement.sign') }}
      </Col>
      <Col :span="18">
        <Upload
          :customRequest="customUpload"
          list-type="picture-card"
          accept="image/bmp"
          :beforeUpload="beforeUpload"
          v-model:file-list="fileList"
          @preview="handlePreview"
          :remove="handleRemove"
        >
          <div v-if="fileList.length < 1">
            <plus-outlined />
            <div class="ant-upload-text">Upload</div>
          </div>
        </Upload></Col
      >
    </Row>

    <Modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </Modal>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { Upload, Modal, Row, Col } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountFormSchema } from './account.data';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  import {
    UpLoadPersonBMP,
    DeletePersonUploadBMP,
    GetUserData,
    GetPersonUploadBMP,
  } from '/@/api/demo/system';

  const { t } = useI18n();
  const { createMessage } = useMessage();

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  const rowId = ref('');
  const fileList = ref([]);
  const previewVisible = ref<boolean>(false);
  const previewImage = ref<string | undefined>('');
  const signFile = ref({
    fileName: '',
    isUpLoad: '',
  });

  const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      GetUserData(rowId.value).then((res) => {
        setFieldsValue(res);
        if (res.signFile !== null) {
          signFile.value = res.signFile;
          GetPersonUploadBMP(rowId.value).then((res) => {
            if (res) {
              fileList.value = [
                {
                  url: res[0],
                },
              ];
            }
          });
        }
      });
    }
    updateSchema([
      {
        field: 'id',
        dynamicDisabled: !!unref(isUpdate),
      },
    ]);
  });

  const getTitle = computed(() =>
    !unref(isUpdate)
      ? t('routes.table.accountManagement.addAccount')
      : t('routes.table.accountManagement.editAccount'),
  );

  // 文件上传
  const customUpload = (e: any) => {
    const formData = new FormData();
    formData.append('file', e.file);
    UpLoadPersonBMP(formData).then((res) => {
      if (res) {
        fileList.value[0].status = 'done';
        signFile.value.fileName = fileList.value[0].name;
        signFile.value.isUpLoad = '1';
        createMessage.success(t('common.uploadSuccess'));
      }
    });
  };

  // 文件上传前
  const beforeUpload = (file: any) => {
    const isBmp = file.name.endsWith('.bmp');
    if (!isBmp) {
      createMessage.error('只能上传.bmp格式的文件！');
      return false;
    }
    return true;
  };

  function getBase64(file: File) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  }

  const handleCancel = () => {
    previewVisible.value = false;
  };
  const handlePreview = async (file: any) => {
    if (!file.url && !file.preview) {
      file.preview = (await getBase64(file.originFileObj)) as string;
    }
    previewImage.value = file.url || file.preview;
    previewVisible.value = true;
  };

  const handleRemove = (file) => {
    DeletePersonUploadBMP(file.name, signFile.value.isUpLoad, rowId.value).then(() => {
      fileList.value = fileList.value.filter((item) => item.uid !== file.uid);
      createMessage.success(t('common.delSuccessText'));
      signFile.value.fileName = '';
      signFile.value.isUpLoad = '';
    });
  };

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      closeModal();
      emit('success', {
        isUpdate: unref(isUpdate),
        values: { ...values, signFile: signFile.value },
      });
      handleClose();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  const handleClose = () => {
    rowId.value = '';
    fileList.value = [];
    previewVisible.value = false;
    previewImage.value = '';
    signFile.value.fileName = '';
    signFile.value.isUpLoad = '';
  };
</script>
